package com.lvdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * Description: 基于Redis实现的唯一id
 * Date:      2022/11/5 20:04
 * author:    LPH
 * version:   V1.0
 */
@Component
public class RedisIdWorker {

    private static StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 开始时间戳
     */
    private static final Long BEGIN_TIMESTAMP = 1640995200L;

    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32;

    /**
     * 获取唯一的id
     * @param keyPrefix 业务的前缀
     * @return 唯一id
     */
    public long nextId(String keyPrefix) {
        // 1. 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;
        // 2. 生成序列号
        // 获取当前日期
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        // String str = timeStamp + String.valueOf(count);
        // 也可以直接返回字符串 ，但是为了效率 ，返回long类型
        // System.out.println(str);
        // 3. 拼接并且返回
        return timeStamp << COUNT_BITS | count;
    }

    public static void main(String[] args) {
        System.out.println(1 << 0);
        LocalDateTime of = LocalDateTime.of(2022, 1, 1, 0, 0);
        long l = of.toEpochSecond(ZoneOffset.UTC);
        System.out.println(l);
    }
}
